﻿using Inovout.Component;
using Inovout.Data.Service;
using Inovout.Membership.Security;
using Inovout.People.Domain;
using Inovout.People.Membership.Domain;
using Inovout.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Inovout.Cloud.Messager.WebPage.Models
{
    public class MembershipUserLogic : RepositoryService<MembershipUser>
    {
        IRepositoryService<MembershipUser> UserService = ComponentRegistry.Resolve<IRepositoryService<MembershipUser>>();
        IRepositoryService<DynamicPasswordCredential> PasswordService = ComponentRegistry.Resolve<IRepositoryService<DynamicPasswordCredential>>();
        public void InsertMembershipUser(Person person)
        {
            IRepositoryService<PersonMembership> PersonService = ComponentRegistry.Resolve<IRepositoryService<PersonMembership>>();
            IRepositoryService<Contact> contactService = ComponentRegistry.Resolve<IRepositoryService<Contact>>();
            PersonMembership pship = PersonService.Query().Where(c => c.Person == person).Select(c => c).SingleOrDefault();
            MembershipUser puser = UserService.Query().Where(c => c.Membership == pship).Select(c => c).SingleOrDefault();
            if (puser == null)
            {
                DynamicPasswordCredential passwordcredential = new DynamicPasswordCredential();
                passwordcredential.Phone= contactService.Query().Where(c => c.Label == ContactMethod.Mobile && c.Person == person).SingleOrDefault().Value;
                MembershipUser user = new MembershipUser();
                user.Membership = pship;
                //ICredential dd = PasswordService.Query().Where(c => c.Mobile == passwordcredential.Mobile).Select(c=>c).SingleOrDefault();
                user.Credentials.Add(passwordcredential);
                UserService.Save(user);
            }
            else
            {
                DynamicPasswordCredential passwordcredential = PasswordService.Query().Where(c => c.User == puser).Select(c => c).SingleOrDefault();
                passwordcredential.Phone = contactService.Query().Where(c => c.Label == ContactMethod.Mobile && c.Person == person).SingleOrDefault().Value;
                puser.Membership = pship;
                puser.Credentials.Add(passwordcredential);
                UserService.Save(puser);
            }
        }
        public void RemoveMenbershipUser(PersonMembership pship)
        {
            MembershipUser user = UserService.Query().Where(c => c.Membership == pship).Select(c => c).SingleOrDefault();
            List<DynamicPasswordCredential> mcs = PasswordService.Query().Where(t => t.User == user).Select(t => t).ToList();
            foreach (DynamicPasswordCredential mc in mcs)
            {
                PasswordService.Delete(mc);
                //user.Credentials.Add(mc);
            }
            UserService.Delete(user);
        }
    }
}